package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Philcan
 * @version 1.0
 * @description: TODO
 * @date 2021/5/27 23:54
 */
@Service
public class MyCenterService {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;

    public Boolean sendVerificationCode(String token) {
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }
        ErrorResult errorResult = this.smsService.sendCheckCode(user.getMobile());
        return errorResult == null;
    }

    public Boolean checkVerificationCode(String code, String token) {
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }

        String redisKey = "CHECK_CODE_" + user.getMobile();
        String value = String.valueOf(this.redisTemplate.opsForValue().get(redisKey));

        if (StrUtil.equals(code, value)) {
            this.redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    public Boolean updatePhone(String token, String phone) {
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }
        Boolean result = this.userService.updatePhone(user.getId(), phone);
        if (result) {
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            this.redisTemplate.delete(redisKey);
        }
        return result;
    }
}
